class Merchant::ActivitiesController < MerchantController
  before_action :set_activity, only: [:show, :edit, :update, :destroy]

  set_tab :activity
  # GET /activities
  # GET /activities.json
  def index
    @activities = Activity.where(merchant_id: current_merchant.id).all
  end

  # GET /activities/1
  # GET /activities/1.json
  def show
  end

  # GET /activities/new
  def new
    @activity = Activity.new
  end

  # GET /activities/1/edit
  def edit
  end

  # POST /activities
  # POST /activities.json
  def create
    @activity = Activity.new(activity_params)
    @activity.merchant_id = current_merchant.id
    respond_to do |format|
      if @activity.save
        if params[:activity][:cover].present?
          format.html {
            render :action => "crop"
          }  
        else
          format.html { redirect_to [:merchant, @activity], notice: 'Activity was successfully created.' }
          format.json { render action: 'show', status: :created, location: @activity }
        end
      else
        format.html { render action: 'new' }
        format.json { render json: @activity.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /activities/1
  # PATCH/PUT /activities/1.json
  def update
    respond_to do |format|
      if @activity.update(activity_params)

        if @activity.cropping?
          @activity.cover.reprocess!
        end

        if params[:activity][:cover].present?
          format.html {
            render :action => "crop"
          }  
        else
          format.html { redirect_to [:merchant, @activity], notice: 'Activity was successfully updated.' }
          format.json { head :no_content }
        end
      else
        format.html { render action: 'edit' }
        format.json { render json: @activity.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /activities/1
  # DELETE /activities/1.json
  def destroy
    @activity.destroy
    respond_to do |format|
      format.html { redirect_to merchant_activities_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_activity
      @activity = Activity.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def activity_params
      params.require(:activity).permit(:cover,:title, :started_at, :end_at, :description, :hot)
    end
end
